package com.block.product.service.union;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.product.model.dto.UniLoginDTO;
import com.block.product.model.param.ProdApiInfoParam;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.service.IUnionLoginService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class YongQianFenqiUnionLoginService implements IUnionLoginService {

    private static final Logger log = LogFactory.getProductUniLog();

    @Override
    public UnionLoginResult checkUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam) {
        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getCheckUrl();
        String mobileMd5 = SecureUtil.md5(uniLoginDTO.getMobile()).toLowerCase();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("app_key", apiInfoParam.getApiKey());
        paramMap.put("user_md5",mobileMd5);

        String sign0 = this.getSignContent(paramMap);
        String sign = SecureUtil.md5(sign0 + apiInfoParam.getApiSecret());

        paramMap.put("sign", sign);

        log.info("【用钱分期】撞库开始【queryUrl】{}【paramMap】{}", checkUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl)
                .form(paramMap)
                .execute().body();
        log.info("【用钱分期】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer status = resultObject.getInteger("status");
        String info = resultObject.getString("info");

        loginResult.setCode(String.valueOf(status));
        loginResult.setMessage(info);
        loginResult.setResultInfo(result);
        loginResult.setParamInfo(JSON.toJSONString(paramMap));

        if (StrUtil.equals(String.valueOf(status), "1")){

            JSONObject data = resultObject.getJSONObject("data");
            String user_md5 = data.getString("user_md5");
            /**
             * 命中结果
             * 命中:返回手机号MD5 撞库了，老用户
             * 未命中:返回空 撞库成功，新用户 可联登
             */
            if (StrUtil.isEmpty(user_md5)){
                loginResult.setSuccess(true);
            }
        }
        return loginResult;
    }

    @Override
    public UnionLoginResult loginUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam,String resultInfo) {

        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getLoginUrl();
        String mobile = uniLoginDTO.getMobile();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("app_key", apiInfoParam.getApiKey());
        paramMap.put("mobile",mobile);
        paramMap.put("platform", "1");
        paramMap.put("timestamp", String.valueOf(System.currentTimeMillis()));

        String sign0 = this.getSignContent(paramMap);
        String sign = SecureUtil.md5(sign0 + apiInfoParam.getApiSecret());

        paramMap.put("sign", sign);

        log.info("【用钱分期】联登开始【queryUrl】{}【paramMap】{}", checkUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl)
                .form(paramMap)
                .execute().body();
        log.info("【用钱分期】联登结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer status = resultObject.getInteger("status");
        String info = resultObject.getString("info");

        loginResult.setCode(String.valueOf(status));
        loginResult.setMessage(info);
        loginResult.setResultInfo(result);
        loginResult.setParamInfo(JSON.toJSONString(paramMap));

        if (StrUtil.equals(String.valueOf(status), "1")){

            JSONObject data = resultObject.getJSONObject("data");
            String code = data.getString("code");
            String skip_url = data.getString("skip_url");

            if (StrUtil.equals(String.valueOf(code), "1")){
                loginResult.setSuccess(true);
                loginResult.setLoginUrl(skip_url);
            }
        }
        return loginResult;
    }

    private String getSignContent( Map<String, Object> paramMap){
        Set<String> keySet = paramMap.keySet();
        List<String> keyList = JSON.parseArray(JSON.toJSONString(keySet), String.class);
        Collections.sort(keyList);

        StringBuilder stringBuilder = new StringBuilder();
        for (String key : keyList) {
            String value = (String) paramMap.get(key);
            stringBuilder.append(StrUtil.format("{}={}&", key, value));
        }

        String substring = stringBuilder.substring(0, stringBuilder.length() - 1);
        return substring;
    }

}
